package com.mediacloud.app.newsmodule.activity;


import static com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.getAppServerConfigInfo;

import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentTransaction;

import com.chinamcloud.collect.AcquisitionManager;
import com.eventTrack.CDPTrackReportManager;
import com.mediacloud.app.appfactory.cache.UserRecommend;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.ImageKitKt;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.eventbus.control.VideoDetailControl;
import com.mediacloud.app.model.eventbus.event.LoginEvent;
import com.mediacloud.app.model.eventbus.event.VideoDetailEvent;
import com.mediacloud.app.model.eventbus.mdoel.afpvideo.AppVideoAdItem;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.ReadDataReciver;
import com.mediacloud.app.model.news.ShowSwitch;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.broadcast.PowerStateReciver;
import com.mediacloud.app.newsmodule.fragment.NotifyMicroEvent;
import com.mediacloud.app.newsmodule.fragment.video.vod.VideoVodDetailFragment;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.DisplayCutoutManager;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker;
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker;
import com.mediacloud.app.newsmodule.utils.VideoAddressGet;
import com.mediacloud.app.reslib.analysis.AnalysisUtils;
import com.mediacloud.app.reslib.config.NewsDetailStyleConfig;
import com.mediacloud.app.reslib.enums.ListStyle;
import com.mediacloud.app.reslib.enums.TitileType;
import com.mediacloud.app.reslib.enums.XKey;
import com.mediacloud.app.user.model.UserInfo;
import com.tencent.mmkv.MMKV;
import com.yoake.media.player.XPlayer;
import com.yoake.media.player.utils.XVideoBitRate;
import com.yoake.media.player.utils.XVideoItem;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.LinkedHashSet;
import java.util.List;

import xyz.doikki.videoplayer.player.VideoView;


/**
 * 视频VR直播
 */
public class VideoLiveVRDetailActivity extends StyleSetActivity implements DataInvokeCallBack<ArticleItemReciver> {
    protected boolean isAutoPlay;
    public XPlayer vrPlayer;
    NewsDetailInvoker newsDetailInvoker;
    protected Handler handler = new RecommendClickHandle();
    VideoVodDetailFragment fragment;
    boolean isOutView = false;
    PowerStateReciver powerStateReciver;
    ShowSwitch showSwitch;
    VideoDetailControl videoDetailControl;
    //支付相关

    LinearLayout broccoliLayout;
    View vodBottomContent;
    private View mErrorView;
    // private TextView emptyTipsText;
    private ImageView imagNowork;
    long  mTyReportStartTime=0;
    long  mTyReportEndTime=0;

    @Override
    public boolean showTitleBar() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isCommentDialog=true;
        videoDetailControl = new VideoDetailControl();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        super.onCreate(savedInstanceState);

        Uri uriData = getIntent().getData();
        if (uriData != null) {
            String articleid = uriData.getQueryParameter("articleid");
            String title = uriData.getQueryParameter("title");
            String cname = uriData.getQueryParameter("cname");
            String tag = uriData.getQueryParameter("tag");
            catalogItem = new CatalogItem();
            catalogItem.setCatname(cname);
            articleItem = new ArticleItem();
            try {
                articleItem.setTitle(title);
                articleItem.setId(Long.valueOf(articleid));
            } catch (Exception e) {
            }
        } else {
            catalogItem = getIntent().getParcelableExtra("catalog");
            articleItem = getIntent().getParcelableExtra("data");
            if (articleItem == null) {
                articleItem = ArticleItem.praseIntentDataToArticleItem(getIntent(), TypeX.NEWS.VIDEO);
            }
        }
        if (articleItem != null) {
            readStatus();
            showSwitch = articleItem.getmShowSwitch();
        }
        if (catalogItem == null) {
            catalogItem = new CatalogItem();
        }

        vodBottomContent = Utility.findViewById(mRootView, R.id.vodBottomContent);
        broccoliLayout = Utility.findViewById(mRootView, R.id.broccoliLayout);
        boolean isLeftImgMode = ListStyle.TotoalStyle.LEFT_IMAGE.equals(serverAppConfigInfo.getContent_list());
        if (isLeftImgMode) {
            for (int i = 0; i < 3; i++) {
                broccoliLayout.addView(LayoutInflater.from(this).inflate(R.layout.layout_broccoli21, null));
            }
        } else {
            for (int i = 0; i < 3; i++) {
                broccoliLayout.addView(LayoutInflater.from(this).inflate(R.layout.layout_broccoli22, null));
            }
        }
        vrPlayer = Utility.findViewById(mRootView, R.id.vrPlayer);
        vrPlayer.setRelease(false);
        vrPlayer.getPrepareView().setVisibleThumb(false);
        vrPlayer.getCompleteView().setVisibleThumb(false);
        vrPlayer.setPosterAndBackGround( ImageKitKt.buildUrl(3,articleItem.getLogo()), ContextCompat.getDrawable(this,R.drawable.cctv7_loading_img));
        getLifecycle().addObserver(vrPlayer);
        mErrorView = Utility.findViewById(mRootView, R.id.error_view);
        imagNowork = mErrorView.findViewById(R.id.image_loading);
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.net_not_give_force);
        String network = serverAppConfigInfo.getNetwork();
        FunKt.load(imagNowork, network, drawable);
        newsDetailInvoker = new NewsDetailInvoker(this);
        isAutoPlay = MMKV.defaultMMKV().decodeBool(XKey.AUTO_PLAY, false);
        vrPlayer.setAutoPlay(isAutoPlay);
        if (articleItem == null)
            return;
        fragment = new VideoVodDetailFragment();

        LinkedHashSet<String> linkedHashSet = getAppServerConfigInfo(this).getNewsDetailConfig().getLinkedHashSet();
        if(!linkedHashSet.contains(NewsDetailStyleConfig.COLLECT_BUTTON) && !linkedHashSet.contains(NewsDetailStyleConfig.SHARE_BUTTON)){
            vrPlayer.getTitleView().hideTitleMoreView();
            vrPlayer.getErrorView().hideTitleMoreView();
        }

        KillMusicUtils.stopAPS(this);
        vrPlayer.setOnTitleMoreClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if(vrPlayer.isFullScreen()){
                        vrPlayer.getController().getControllerInstance().hide();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                moreClicked();
            }
        });
        getVideoDetail();


        powerStateReciver = new PowerStateReciver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
        intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        registerReceiver(powerStateReciver, intentFilter);
        setNewsTitle();


        onPageStart();
        showPageTransition();
        //设置使用刘海屏幕区域
        new DisplayCutoutManager(this).set(WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES);
//        vrPlayer.setScreenListener(new VRFullScreenListener() {
//            @Override
//            public void onScreenChange(boolean b) {
//                if(b){
//                    WindowManager.LayoutParams windowLP = getWindow().getAttributes();
//                    windowLP.alpha = 1f;
//                    getWindow().setAttributes(windowLP);
//                }else{
//                    WindowManager.LayoutParams windowLP = getWindow().getAttributes();
//                    windowLP.alpha = 0f;
//                    getWindow().setAttributes(windowLP);
//                }
//            }
//        });
        swipeBackLayout.setSupportSwipe(false);
    }


    public ArticleItem getArticleItem() {
        return articleItem;
    }

    @Override
    protected boolean getFitSystemWindow() {
        return true;
    }


    protected void setNewsTitle() {
        int base = serverAppConfigInfo.getBase();
        if (base == TitileType.FRAME) {
            setFrameTypeTitle();
        } else if (base == TitileType.NAVIGATE) {
            setTitle(catalogItem != null ? catalogItem.getCatname() : "");
        } else if (base == TitileType.NEWS_TITLE) {
            setTitle(articleItem != null ? articleItem.getTitle() : "");
        } else if (base == TitileType.NOTITLE) {
            setTitle("");
        }

    }

    Object mark = System.currentTimeMillis();


    protected void getVideoDetail() {

        CatalogItem catalogItem = getIntent().getParcelableExtra("catalog");
        if (catalogItem == null) {
            catalogItem = new CatalogItem();
            String nid = getIntent().getStringExtra("navigate_id");
            if (nid == null) {
                nid = "";
            }
            catalogItem.setCatid(nid);
        }
        String navigate_id = catalogItem != null ? catalogItem.getCatid() : "";
        UserInfo info = UserInfo.getUserInfo(getBaseContext());
        videoDetailControl.getVideoDetail("" + articleItem.getId(), navigate_id, info.getUserid(), mark);
    }


    @Override
    public void onBackPressed() {
        if (shareWrap.isShowing()) {
            shareWrap.dismiss();
            isOutView = false;
        }
        if(vrPlayer.isFullScreen()){
            vrPlayer.onBackPressed();
        }else{
            finish();
        }

    }


    @Override
    public void finish() {
        super.finish();
        CDPTrackReportManager.getInstance().NewsContentDetailView(articleItem,(System.currentTimeMillis()-inTime)/1000);
        if (articleItem!=null&&mTyReportStartTime>0) {
            mTyReportEndTime=System.currentTimeMillis();
        }
        if (readStatusInvoker != null)
            readStatusInvoker.destory();
        readStatusInvoker = null;
        if (videoDetailControl != null) {
            videoDetailControl.dispose();
            videoDetailControl = null;
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }

        if (newsDetailInvoker != null) {
            newsDetailInvoker.destory();
        }

        try {
            unregisterReceiver(powerStateReciver);
            if (fragment != null) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.remove(fragment);
                transaction.commitNowAllowingStateLoss();
            }
        } catch (Exception ex) {
        }
        if (vrPlayer!=null){
            vrPlayer.release();
        }
    }

    @Override
    public int getStatusBarColor() {
        if (vrPlayer != null && vrPlayer.isFullScreen())
            return Color.TRANSPARENT;
        return Color.BLACK;
    }

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_activity_videovod_vr_detail;
    }


    protected class RecommendClickHandle extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //分享
            if (msg.what == 0) {
                return;
            }
            //点赞
            else if (msg.what == 100) {
                fragment.setVideoReades(msg.arg1);
            }
            try {
                ArticleItem articleItem = (ArticleItem) msg.obj;
                if (articleItem == null) return;
                if (articleItem.getId() == articleItem.getId())
                    return;
                vrPlayer.setAutoPlay(true);

                getVideoDetail();
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "" + e.getMessage());
            }
        }
    }



    public String mp4Data;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void reciveVideoDetail(VideoDetailEvent<List<AppVideoAdItem>, ArticleItemReciver> event) {
        if (event.getType() != VideoDetailEvent.ResultDetail && event.getData().otherData != mark)
            return;

        success(event.getData());
    }


    @Override
    public void success(ArticleItemReciver data) {

        if (data.state && data.articleItem != null) {
            articleItem = data.articleItem;
            sendExposureEvent();
            refreshBottomStyle(data.articleItem, 1);
            UserRecommend.addItemKeyWord(articleItem, this);
            articleItem.mShowSwitch = showSwitch;
            if (hadAdded) {
                fragment.setArticleItem(articleItem);
            }

            initDetailFragment(data, true);
            //  vrPlayer.getPoster().load(articleItem.getLogo(),AppFactoryGlobalConfig.getDefaultImageLoadDrawable(),0);
            setVideoContent(articleItem.getVideo());

        }
        startAddIntegralCounter();
    }

    private void startAddIntegralCounter(){
        AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (articleItem == null) {
                    return;
                }
//                Addintegral.addintegral(VideoLiveVRDetailActivity.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0",articleItem);
            }
        });
    }

    public void hiddBroccoliLayout() {
        broccoliLayout.setVisibility(View.GONE);
        mErrorView.setVisibility(View.GONE);
    }

    private void setVideoContent(String videoStr) {
        try {
            JSONObject video = new JSONObject(videoStr);
            String cdn = video.optString("cdnConfigEncrypt");
            String poster = video.optString("poster", "");
            JSONArray tsAddress = VideoAddressGet.getAddress(video);
            if (tsAddress != null) mp4Data = tsAddress.toString();
//            VideoPlayObj videoPlayObj = new VideoPlayObj();
//            videoPlayObj.setTitle(articleItem.getTitle());
//            videoPlayObj.setVID(articleItem.getVid());
//            videoPlayObj.setCdn_iv(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv);
//            videoPlayObj.setCdn_key(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key);
            XVideoItem videoItem = new XVideoItem(articleItem.getTitle());

            for (int i = 0; tsAddress != null && i < tsAddress.length(); i++) {
                JSONObject line = tsAddress.optJSONObject(i);
                String url = line.optString("url");
                String title = line.optString("title");
                if (!TextUtils.isEmpty(url)) {
                    videoItem.getBitRates().add(new XVideoBitRate(title,url,null));
                }

            }


            vrPlayer.addVideoItem(videoItem,true);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "" + e.getMessage());

        }
    }

    boolean hadAdded = false;

    protected void initDetailFragment(ArticleItemReciver data, boolean appfacBuy) {
        if (hadAdded)
            return;
        Bundle args = new Bundle();
        //ArticleItem nItem = ArticleItem.parse(data.articleItem.orginDataObject);
        //   nItem.setContent(null);
        args.putParcelable("data", data.articleItem);
        args.putParcelable("catalog", catalogItem);
        args.putBoolean("appfacBuy", appfacBuy);
        args.putParcelableArrayList("components", data.components);
        fragment.setArguments(args);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.vodBottomContent, fragment);
        transaction.show(fragment);
        transaction.commitAllowingStateLoss();
        hadAdded = true;
    }

    @Override
    public void fault(Object data) {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

    }

    ReadStatusInvoker readStatusInvoker;

    public void readStatus() {
        readStatusInvoker = new ReadStatusInvoker(new DataInvokeCallBack<ReadDataReciver>() {
            @Override
            public void success(ReadDataReciver data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, data.virtualIncrement);
                Message msg = new Message();
                msg.what = 100;
                msg.arg1 = (int) data.reads;
                handler.sendMessageDelayed(msg, 2000);
            }

            @Override
            public void fault(Object data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, AnalysisUtils.DefaultVirtualIncrement);
            }
        });
        readStatusInvoker.readStatistics(articleItem.getId() + "", 1);
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readEnter(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readExit(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent loginEvent) {
        //20200117修复登录后页面不刷新导致无法更新付费状态的bug
        if (UserInfo.getUserInfo(this).isLogin()) {
            getVideoDetail();
        }
    }

    @Override
    public void noNetwork() {
        mErrorView.setVisibility(View.VISIBLE);
        //  emptyTipsText.setText("网络请求失败，请点击重试");
        mErrorView.setOnClickListener(v -> {
            if (hasNetWork)
                getVideoDetail();
            else showNetWorDialog();
        });
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (vrPlayer != null && !isFinish) {
            if (commentIsOpen) {
                commentIsOpen =false;
                if (vrPlayer.getPlayStateAtLifecycleOwnerPause() == VideoView.STATE_PLAYING
                        ||vrPlayer.getPlayStateAtLifecycleOwnerPause() == VideoView.STATE_PREPARING
                        ||vrPlayer.getPlayStateAtLifecycleOwnerPause() == VideoView.STATE_PREPARED) {
                    vrPlayer.start();
                }
            }
        }

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void restorePause(NotifyMicroEvent event){
        //防止点击home键，评论框pause了，视频也应该pause
        if (vrPlayer != null){
            if (event.getPlay())
                vrPlayer.resume();
            else
                vrPlayer.pause();
        }
    }
}